<template>
  <div class="page-container">
    <van-nav-bar title="考勤打卡" fixed placeholder />
    
    <!-- 打卡状态 -->
    <div class="status-card">
      <van-cell center 
        :title="currentStatus.title" 
        :value="currentStatus.label" 
        :title-style="{ color: currentStatus.color }"
      />
      <div class="button-group">
        <van-button 
          v-if="showClockButton"
          :type="currentStatus.buttonType" 
          size="small"
          @click="handleClock"
        >
          {{ currentStatus.buttonText }}
        </van-button>
      </div>
    </div>
  <!-- 添加加载状态提示 -->

    <!-- 打卡记录 -->
    <van-cell-group inset>
      <van-cell title="今日打卡记录" />
      <van-cell 
        v-for="(item,index) in todayRecords" 
        :key="index"
        :title="formatType(item.attendanceType)"
        :value="formatTime(item.clockTime)"
        :value-class="statusClass(item.status)"
      >
        <template #extra>
          <van-tag :type="statusTagType(item.status)">
            {{ statusText(item.status) }}
          </van-tag>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 定位按钮 -->
    <van-button 
      class="locate-btn" 
      type="primary" 
      icon="location"
      @click="handleLocate"
    />
    
    <!-- 地图容器 -->
    <div id="map-container" class="map-box"></div>
    
  </div>
  <van-overlay :show="!realLocationLoaded" class="location-overlay">
    <div class="loading-container">
      <van-loading size="24px" color="#1989fa" vertical>定位中...</van-loading>
    </div>
  </van-overlay>  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import useUserInfoStore from "@/stores/userInfo.js";
import { useRecordStore } from '@/stores/record';
const attendanceData = useRecordStore()
import {getUserInfoService} from "@/api/user";
const userInfoStore = useUserInfoStore()
import { Toast } from 'vant'
import moment from 'moment'
import {handleClockPageService,getTodayRecords,getWorkTimeConfigService} from '@/api/attendance'
import { checkIsLeaveService} from '@/api/leave'
import AMapLoader from '@amap/amap-jsapi-loader'
import { 
  showToast,          // 通用显示方法
  showSuccessToast,   // 成功专用
  showFailToast ,      // 失败专用
  showNotify
} from 'vant'
// 地图实例
let map = null
let geolocation = null
const status = ref({ 
    value: 0,
    title: '上班打卡',
    label: '未打卡',
    color: '#ee0a24',
    buttonType: 'primary',
    buttonText: '立即打卡'
  })
  const getUserInfo = async () => {
  const result = await getUserInfoService();
    userInfoStore.setUserInfo(result.data)
  console.log(userInfoStore.userInfo.userAccount);
  const userInfo= ref()
  userInfo.value = {...userInfoStore.userInfo }
  console.log(userInfo);
  
} 
// 系统状态
const currentDate = ref(moment().format('YYYY-MM-DD'))
const employeeId = userInfoStore.userInfo.id
const attendanceType = ref(0)
const currentTime = ref(moment().format('HH:mm:ss'))
const longitude = ref()
const latitude = ref()
const isLeave = ref(false)
const realLocationLoaded = ref(false)
const clockTime = ref(moment().format('YYYY-MM-DD HH:mm:ss'))

// 获取打卡时间配置
const getWorkTimeConfig = async () => {
  try {
    const result = await getWorkTimeConfigService()
    workConfig.value = result.data
  } catch (error) {
    console.error('获取打卡时间配置失败:', error)
    ElMessage.error('获取打卡时间配置失败，请检查网络或重试')
  }
}
getWorkTimeConfig()
// 考勤配置
const workConfig = ref({
  workTime: '20:30',
  offTime:  '21:58'
})



// 日期变化检测
const checkDateChange = () => {
  const today = moment().format('YYYY-MM-DD')
  if (currentDate.value !== today) {
    attendanceData.value = []
    currentDate.value = today
  }
}

// 格式化方法
const formatType = (type) => type === 0 ? '上班打卡' : '下班打卡'
const formatTime = (time) => moment(time).format('HH:mm:ss')

// 状态显示
const statusText = (status) => ['正常', '迟到', '早退', '缺勤', '请假',"未下班打卡"][status]
const statusTagType = (status) => status === 0 ? 'success' : 'danger'
const statusClass = (status) => ['status-normal', 'status-late', 'status-early'][status] || ''

// 计算属性
const todayRecords = computed(() => {
  return attendanceData.record
    .filter(item => moment(item.clockTime).isSame(moment(), 'day'))
    .sort((a, b) => moment(a.clockTime) - moment(b.clockTime))
})

const currentStatus = computed(() => {
  const now = moment()
  // 获取时间范围
  const workTime = moment(workConfig.value.workTime, 'HH:mm')
  const offTime = moment(workConfig.value.offTime, 'HH:mm')
  const workStartRange = [workTime.clone().subtract(1, 'hours'), workTime.clone().add(1, 'hours')]
  const workEndRange = [offTime.clone().subtract(1, 'hours'), offTime.clone().add(1, 'hours')]
 
  const twoHoursAfterOffTime = workTime.clone().add(2, 'hours')

  if (isLeave.value) {
    return {
      ...status.value,
      label: '今日请假',
      buttonText: '无需打卡',
      color: '#969799',
      buttonType: 'default'
    }
  }

  // 打卡次数限制
  if (attendanceData.record.length >= 2) {
    return {
      ...status.value,
      label: '今日已完成',
      title: '无需打卡',
      buttonText: '无需打卡',
      color: '#969799',
      buttonType: 'default',
    }
  }

  if (status.value.value === 3) {
    return {
      ...status.value,
      label: '已缺勤',
      buttonText: '无需打卡',
      color: '#ff0000',
      buttonType: 'default'
    }
  }
  // 状态判断逻辑


  // 状态显示增强
  let timeRange = ''
  
  if (attendanceType.value === 0) { 
    timeRange = `${workStartRange[0].format('HH:mm')}-${workStartRange[1].format('HH:mm')}`   
    status.value.value = now.isAfter(workTime) ? 1 : 0
    console.log(status.value.value  );
    return { ...status.value,
      title: '上班打卡',
      label: now.isAfter(workTime) ? 
        `已迟到（可打卡时间：${timeRange}）` : 
        `正常（可打卡时间：${timeRange}）`,
      color: now.isAfter(workTime) ? '#ee0a24' : '#07c160',
      value: now.isAfter(workTime) ? 1 : 0
    } 
  } 
  
  if (attendanceType.value === 1) {
    timeRange = `${workEndRange[0].format('HH:mm')}-${workEndRange[1].format('HH:mm')}`
    status.value.value = now.isBefore(offTime) ? 2 : 0 
    return { 
      ...status.value,
      title: '下班打卡',
      label: now.isBefore(offTime) ? 
        `已早退（可打卡时间：${timeRange}）` : 
        `正常（可打卡时间：${timeRange}）`,
      color: now.isBefore(offTime) ? '#ee0a24' : '#07c160',
      value: now.isBefore(offTime) ? 2 : 3
    };
  }
  return status.value
})

const showClockButton = computed(() => currentStatus.value.buttonText !== '无需打卡')

// 地图初始化
const initMap = async () => {
  if (attendanceData.record.length >= 1) {
    attendanceType.value = 1
  }
  const res =await getTodayRecords()
  console.log(res.data);
  
  // 安全处理响应数据
  if (Array.isArray(res.data) && res.data.length > 0) {
    const firstRecord = res.data[0]
    status.value.value = firstRecord?.status ?? 0 // 添加空值保护
    console.log('Received status:', firstRecord.status)
  } else {
    status.value.value = 0 // 设置默认状态
    console.warn('Empty attendance data')
  }

  attendanceData.removeRecord()
  attendanceData.setRecord(res.data)
  try {
    const AMap = await AMapLoader.load({
      key: 'af64e6b0a16faf7463ec5aa0a9701544',
      securityJsCode: '027071d5e5e69b5cceb2e1d515ebd810',
      version: '2.0',
      plugins: ['AMap.Geolocation']
    })

    map = new AMap.Map('map-container', {
      zoom: 14,
      features: ['bg', 'point'], // 仅请求背景和标注
      viewMode: '2D',            // 2D模式减少数据量
      resizeEnable: true,
      timeout: 5000, // 从25s缩短到5s
      maximumAge: 0, // 禁用缓存
      enableHighAccuracy: true // 强制高精度模式
    })

    // 定位控件
    geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,  // 启用GPS
      timeout: 15000,            // 增加超时时间
      maximumAge: 0,            // 禁用缓存    
      showMarker: true,
      showButton: false,
      useNative: true, // 使用原生定位
      GeoLocationFirst: true // 优先使用浏览器定位
    })
    map.addControl(geolocation)

    // 首次定位
    const locate = () => {
      geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          longitude.value = result.position.lng
          latitude.value = result.position.lat
          map.setCenter([result.position.lng, result.position.lat])
          showUserLocation(result.position, AMap)
          realLocationLoaded.value = true
        } else {
          console.error('定位失败:', result.message)
          showNotify({ type: 'danger', message: '定位失败，尝试重新定位' })
          // 重试定位
          setTimeout(locate, 5000) 
        }
      })
    }
    locate()

  } catch (error) {
    console.error('地图初始化失败:', error)
    showNotify({ type: 'danger', message:"地图加载失败" })
  }
}

// 用户位置标记
const showUserLocation = (position, AMap) => {
  new AMap.Marker({
    position: position,
    map: map,
    content: `
      <div class="user-location">
        <div class="pulse"></div>
        <div class="dot"></div>
      </div>
    `,
    offset: new AMap.Pixel(-10, -10)
  })
  
  // 居中显示
  map.setCenter(position)
}

// 打卡处理
const handleClock = async () => {
  if (!longitude.value || !latitude.value) return  showFailToast('请等待定位完成')
  if (attendanceData.record.length >= 2) return showFailToast('今日打卡已完成')
  
  const now = moment()
  const workTime = moment(workConfig.value.workTime, 'HH:mm')
  const offTime = moment(workConfig.value.offTime, 'HH:mm')

  // 时间范围验证
  let isValidTime = false
  if (attendanceType.value === 0) {
    // 上班打卡时间范围：前1小时 ~ 上班时间
    isValidTime = now.isBetween(
      workTime.clone().subtract(1, 'hours'),
      workTime.clone().add(1, 'hours'),
      null,
      '[]'
    )
  } else {
    // 下班打卡时间范围：下班时间 ~ 后1小时
    isValidTime = now.isBetween(
      offTime.clone().subtract(1, 'hours'),
      offTime.clone().add(1, 'hours'),
      null,
      '[]'
    )
  }

  if (!isValidTime) {
    return showNotify({ type: 'danger', message:"未到打卡时间" });
  }
  const params = {
    longitude: longitude.value,
    latitude: latitude.value,
    employeeId: employeeId,
    attendanceType: attendanceType.value,
    status: status.value.value,
    clockTime: clockTime.value,
  }
  console.log("employeeId:"+employeeId);
  
  if (!longitude.value || !latitude.value) {
    return showFailToast('请等待定位完成')
  }
  const result = await handleClockPageService(params)

  const res =await getTodayRecords()
  attendanceData.removeRecord()
  attendanceData.setRecord(res.data)

  console.log(attendanceData.record) ;
  
  
  showNotify({ type: 'success', message: attendanceType.value === 0 ? '上班打卡成功' : '下班打卡成功' });
  attendanceType.value = attendanceType.value === 0 ? 1 : 0
  console.log("attendanceType:"+attendanceType.value);
}

// 手动定位
const handleLocate = () => {
  if(geolocation){
    geolocation.getCurrentPosition()
  }
}
const checkIsLeave = async () => {
    const res = await checkIsLeaveService(); 
    console.log(res);
    console.log(res.data);
    if (res.data) {
      isLeave.value = res.data;
    }
}
onMounted(() => {
  
  getUserInfo();
  checkIsLeave(); 
  initMap()
  setInterval(() => {
    currentTime.value = moment().format('HH:mm:ss')
    checkDateChange()
  }, 1000)
})
</script>

<style scoped>
.page-container {
  position: relative;
  padding-bottom: 50px;
}

.status-card {
  margin: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.map-box {
  width: 100%;
  height: 300px;
  margin: 16px 0;
  border-radius: 8px;
  overflow: hidden;
}

.locate-btn {
  position: fixed;
  right: 16px;
  bottom: 100px;
  z-index: 999;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

.status-normal { color: #07c160; }
.status-late { color: #ee0a24; }
.status-early { color: #ff976a; }

.user-marker {
  width: 20px;
  height: 20px;
  background: #07c160;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(0.8); opacity: 1; }
  100% { transform: scale(2); opacity: 0; }
}
/* 定位加载样式 */
.location-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
}

.loading-container {
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loading-container :deep(.van-loading__text) {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}
</style>